package com.ruoyi.web.util;

import com.aspose.words.*;

import java.io.*;

public class DocConvertPdf {
    static { getLicense(); }
    public static void main(String[] args) throws Exception {

        for (int i = 0; i < 2; i++) {
            long l1 = System.currentTimeMillis();
            FileOutputStream os  = new FileOutputStream(new File("D:\\111.pdf"));
            docTurnPdf("D:\\111.docx",os);
            long l2 = System.currentTimeMillis();
            System.out.println(l2-l1);
        }
    }
    public static boolean getLicense(){
        boolean result = false;
        try {
            String fontFolder = "C:\\Windows\\Fonts";
//            String fontFolder = "/usr/share/fonts/";
            InputStream is = DocConvertPdf.class.getClassLoader().getResourceAsStream("license.xml"); //Test要替换成当前类名  license.xml应放在..\WebRoot\WEB-INF\classes路径下
            License AsposeLic = new License();
            AsposeLic.setLicense(is);
            FontSettings.setFontsFolder(fontFolder, false);//设置字体文件夹
            if (is != null) {
                is.close();
            }
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * doc转pdf
     * @param sourceFileName doc文档的路径 如：C:\Users\weipc\Desktop\html\询问笔录.doc
     * @param os 将要生成的pdf路径 如：C:\Users\weipc\Desktop\html\询问笔录.pdf
     * @throws Exception
     */
    public static boolean docTurnPdf(String sourceFileName,FileOutputStream os) {
        try {
            Document doc = new Document(sourceFileName);//Address是将要被转化的word文档
            doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            os.close();
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
    public static byte[] docTurnPdf(InputStream inputStream) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte[] result = null;
        try {
            Document doc = new Document(inputStream);//Address是将要被转化的word文档
            doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            result = os.toByteArray();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
